<template>
    <div>
      <el-container style="height: 700px; border: 1px solid #eee">
        <el-header style="font-size: 40px; background-color: rgb(238,241,246);">学生成绩管理系统</el-header>
        <el-container>
          <el-aside width="200px"><el-menu :default-openeds="['1', '3']">
  
                <el-submenu index="1">
                  <template slot="title"><i class="el-icon-menu"></i>专业</template>
                  <el-menu-item-group>
                    <template slot="title">网安23级</template>
                    <el-menu-item index="1-1">
                      <router-link to="/students" style="text-decoration: none;">学生管理</router-link>
                    </el-menu-item>
                    <el-menu-item index="1-2">
                      <router-link to="/score" style="text-decoration: none;">学生成绩</router-link>
                    </el-menu-item>
                  </el-menu-item-group>
                </el-submenu>
  
                <el-submenu index="2">
                  <template slot="title"><i class="el-icon-message"></i>班级管理</template>
                  <el-menu-item-group>
                    <template slot="title">班级管理</template>
                    <el-menu-item index="2-1">
                      <router-link to="/class" style="text-decoration: none;">班级管理</router-link>
                    </el-menu-item>
                  </el-menu-item-group>
                </el-submenu>
  
                <el-submenu index="3">
                  <template slot="title"><i class="el-icon-message"></i>班级信息管理</template>
                  <el-menu-item-group>
                                <template slot="title">网安2311</template>
                                <el-menu-item index="3-1" @click="fetchStudentsByDeptId('2311')">学生管理</el-menu-item>
                                <el-menu-item index="3-2" @click="fetchScoreByDeptId('2311')">学生成绩</el-menu-item>
                            </el-menu-item-group>
                            <el-menu-item-group title="网安2312">
                                <el-menu-item index="3-3" @click="fetchStudentsByDeptId('2312')">学生管理</el-menu-item>
                                <el-menu-item index="3-4" @click="fetchScoreByDeptId('2312')">学生成绩</el-menu-item>
                            </el-menu-item-group>
                            <el-menu-item-group title="网安2313">
                                <el-menu-item index="3-5" @click="fetchStudentsByDeptId('2313')">学生管理</el-menu-item>
                                <el-menu-item index="3-6" @click="fetchScoreByDeptId('2313')">学生成绩</el-menu-item>
                            </el-menu-item-group>
                </el-submenu>
  
              </el-menu>
            </el-aside>
          <el-main>
            <el-form :inline="true" :model="searchForm" class="search-form">
              <el-form-item label="学号">
                <el-input v-model="searchForm.studentNumber"></el-input>
              </el-form-item>
              <el-form-item label="姓名">
                <el-input v-model="searchForm.name"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
              </el-form-item>
            </el-form>
            <div style="display: flex; justify-content: flex-end;">
              <el-button type="primary" @click="scoreForm">成绩单</el-button>
              <el-button type="primary" @click="handleSortByStudentNumber">按学号排序</el-button>
              <el-button type="primary" @click="handleSortByScore">按成绩排序</el-button>
            </div>
            <el-table :data="computedTableData" border>
              <el-table-column prop="studentNumber" label="学号" width="140"></el-table-column>
              <el-table-column prop="name" label="姓名" width="120"></el-table-column>
              <el-table-column prop="chinese" label="语文成绩"></el-table-column>
              <el-table-column prop="math" label="数学成绩"></el-table-column>
              <el-table-column prop="english" label="英语成绩"></el-table-column>
              <el-table-column prop="java" label="java成绩"></el-table-column>
              <el-table-column prop="sports" label="体育成绩"></el-table-column>
              <el-table-column prop="total" label="总分"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                  <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              background
              layout="prev, pager, next"
              :total="totalData"
              :page-size="pageSize"
              :current-page="currentPage"
              :hide-on-single-page="true"
              @current-change="handlePageChange">
            </el-pagination>
            <el-dialog :visible.sync="editDialogVisible" title="编辑学生">
              <el-form :model="editEmployee" label-width="80px">
                <el-form-item label="学号">
                  <el-input v-model="editEmployee.studentNumber" disabled></el-input>
                </el-form-item>
                <el-form-item label="姓名">
                  <el-input v-model="editEmployee.name"></el-input>
                </el-form-item>
                <el-form-item label="语文成绩">
                  <el-input v-model="editEmployee.chinese"></el-input>
                </el-form-item>
                <el-form-item label="数学成绩">
                  <el-input v-model="editEmployee.math"></el-input>
                </el-form-item>
                <el-form-item label="英语成绩">
                  <el-input v-model="editEmployee.english"></el-input>
                </el-form-item>
                <el-form-item label="Java 成绩">
                  <el-input v-model="editEmployee.java"></el-input>
                </el-form-item>
                <el-form-item label="体育成绩">
                  <el-input v-model="editEmployee.sports"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitEdit">保存</el-button>
                  <el-button @click="editDialogVisible = false">取消</el-button>
                </el-form-item>
              </el-form>
            </el-dialog>
          </el-main>
        </el-container>
      </el-container>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  
  export default {
    data() {
      return {
        tableData: [],
        totalData: 0, // 总数据量
        pageSize: 10, // 展示数据量
        currentPage: 1, // 当前页
        searchForm: {
          studentNumber: null,
          name: ''
        },
        isScoreSorted: false,
        addDialogVisible: false,
        newEmployee: {
          studentNumber: '',
          name: '',
          chinese: '',
          math: '',
          english: '',
          java: '',
          sports: ''
        },
        editDialogVisible: false, 
        editEmployee: {
          studentNumber: '',
          name: '',
          chinese: '',
          math: '',
          english: '',
          java: '',
          sports: '',
          sum:''
        }
      };
    },
    mounted() {
      this.handlePageChange(1);
    },
    computed: {
      paginatedData() {
        return this.tableData;
      },
      computedTableData() {
        return this.tableData.map(row => {
          const total = (row.chinese || 0) + (row.math || 0) + (row.english || 0) + (row.java || 0) + (row.sports || 0);
          return {
           ...row,
            total: total
          };
        });
      }
    },
    methods: {
      async handleSearch() {
        this.currentPage = 1;
        await this.fetchSearchData();
      },
  
      async scoreForm() {
    let classId = this.$route.params.deptId;
    try {
        const response = await axios.get(`http://localhost:8080/generateByClass/${classId}`);
        const result = response.data;
        if (result.code === 1 && result.msg === "success") {
            alert('创建成功');
        } else {
            alert('创建不成功');
        }
    } catch (error) {
        console.error('请求失败：', error);
        alert('请求失败，请检查网络或联系管理员');
    }
},
  
      async handlePageChange(newpage) {
      this.currentPage = newpage;
      try {
        if(!this.isScoreSorted){
          await this.fetchData();
          console.log('当前选中的页码是,' + newpage);
        }else if(this.isScoreSorted){
          await this.fetchRankData();
          }
      } catch (error) {
          alert('请求失败，请检查网络或联系管理员');
      }
  },    
  
  handleSortByScore() {
          this.isScoreSorted = true;
          this.fetchRankData();
      },
  handleSortByStudentNumber() {
          this.isScoreSorted = false;
          this.fetchData();
      },
  
  async fetchRankData() {
        try {
          const response = await axios.get('http://localhost:8080/scoreRank', {
            params: {
              page: this.currentPage,
              pageSize: this.pageSize
            }
          });
          const result = response.data;
          if (result.code === 1 && result.msg === "success" && result.data) {
            this.tableData = result.data.rows;
            this.totalData = result.data.total;
          } else {
            alert('请求不成功，请检查网络或联系管理员');
          }
        } catch (error) {
          alert('请求失败，请检查网络或联系管理员');
        }
      },
  
  
      async fetchData() {
        try {
          let classId=this.$route.params.deptId;
          const response = await axios.get('http://localhost:8080/classScore', {
            params: {
              page: this.currentPage,
              pageSize: this.pageSize,
              deptId:classId
            }
          });
          const result = response.data;
          if (result.code === 1 && result.msg === "success" && result.data) {
            this.tableData = result.data.rows;
            this.totalData = result.data.total;
          } else {
            alert('请求不成功，请检查网络或联系管理员');
          }
        } catch (error) {
          alert('请求失败，请检查网络或联系管理员');
        }
      },
  
      async handleDelete(index, row) {
        try {
          await axios.delete(`http://localhost:8080/score/${row.id}`);
          this.tableData.splice(index, 1);
          alert('删除成功');
        } catch (error) {
          alert('删除失败，请检查网络或联系管理员');
        }
      },
      handleAdd() {
        this.addDialogVisible = true;
      },
  
      handleEdit(index, row) {
        this.editDialogVisible = true;
        this.editEmployee = {...row};
        this.fetchEditData(row.studentNumber);
      },
  
      async fetchEditData(studentNumber) {
        try {
          const response = await axios.get(`http://localhost:8080/score/${studentNumber}`);
          const result = response.data;
          if (result.code === 1 && result.msg === "success" && result.data) {
            this.editEmployee = result.data;
          } else {
            alert('获取学生信息不成功');
          }
        } catch (error) {
          alert('获取学生信息失败，请检查网络或联系管理员');
        }
      },
  
      async fetchSearchData() {
        try {
          const response = await axios.get('http://localhost:8080/findScore', {
            params: {
              page: this.currentPage,
              pageSize: this.pageSize,
              studentNumber: this.searchForm.studentNumber,
              name: this.searchForm.name
            }
          });
          const result = response.data;
            if (result.code === 1 && result.msg === "success") {
                if (result.data) {
                  this.tableData = result.data.rows;
                  this.totalData = result.data.total;
                } else {
                  alert("未找到符合条件的学生");
                }
              }
           else {
            alert('搜索请求不成功，请检查网络或联系管理员');
          }
        } catch (error) {
          alert('搜索请求失败，请检查网络或联系管理员');
        }
      },
  
      async submitEdit() {
        try {
          const response = await axios.put(`http://localhost:8080/score`, this.editEmployee);
          const result = response.data;
          if (result.code === 1 && result.msg === "success") {
            this.editDialogVisible = false;
            this.handlePageChange(this.currentPage);
            alert('编辑成功');
          } else {
            alert('编辑不成功，请检查网络或联系管理员');
          }
        } catch (error) {
          alert('编辑失败，请检查网络或联系管理员');
        }
      },
  
      async fetchStudentsByDeptId(deptId) {
        let classId =deptId;
        this.$router.push(`/${classId}/students`).catch(err => {
        if (err.name!== 'NavigationDuplicated') {
        throw err;}});  
        }, 
  
        async fetchScoreByDeptId(deptId) {
            let classId =deptId;
            this.$router.push(`/${classId}/score`).catch(err => {
        if (err.name!== 'NavigationDuplicated') {
        throw err;}});  
         },
        navigateTo(route) {
            this.$router.push(route);
        }
    }
  };
  </script>
  